//
//  YWShowInspectionLineTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/6.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWShowInspectionLineTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "MJRefresh.h"

#import "MBProgressHUD.h"
#import "YWInspectionMissionModel.h"
#import "YWInspectionMissionManager.h"

#import "YWInspectionTimeLineCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "YWHandler.h"

#import "YWModifyEquipmentInspecLineTableViewController.h"
#import "YWModifyLocationInspecLineTableViewController.h"

@interface YWShowInspectionLineTableViewController ()
@property (nonatomic, strong) YWInspectionLineModel *inspectionLine;
@property (nonatomic, strong) NSArray *infoArray;
@property (nonatomic, strong) NSArray *timeLineDataArray;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UIButton *deleteButton;
@property (nonatomic, strong) UIButton *modifyButton;
@property (nonatomic, weak) MBProgressHUD *HUD;

@end

@implementation YWShowInspectionLineTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"linePreview", nil);//@"路线预览";
    
    _inspectionLine = [[YWInspectionMissionManager shareManager] inspectionLineWithLineId:self.inspectionLineOption.inspectionLineId];
    
    [self setupNotifications];
    [self setupTableView];
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshModifyInspectionLineNotification object:nil];
}

- (void)setupTableView{
    [self.tableView registerClass:[YWInspectionTimeLineCell class] forCellReuseIdentifier:inspectionTimeLineCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    if (_inspectionLine.creator.uniqueId == [YWLoginTool loginUser].uniqueId) {
        self.tableView.tableFooterView = self.footView;
    }
    if (self.inspectionLineOption) {
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
        // 马上进入刷新状态
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)refreshTop{
    YWWeakSelf(weakSelf);
    [[YWInspectionMissionManager shareManager] requestInspectionLineWithInspectionLineId:self.inspectionLineOption.inspectionLineId Complete:^(YWInspectionLineModel *inspectionLine) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView.mj_header endRefreshing];
            if (inspectionLine) {
                weakSelf.inspectionLine = [[YWInspectionMissionManager shareManager] inspectionLineWithLineId:inspectionLine.inspectionLineId];
                if (weakSelf.inspectionLine.creator.uniqueId == [YWLoginTool loginUser].uniqueId) {
                    weakSelf.tableView.tableFooterView = weakSelf.footView;
                }
            }
            weakSelf.infoArray = nil;
            weakSelf.timeLineDataArray = nil;
            [weakSelf.tableView reloadData];
        });
    }];
}

- (NSArray *)infoArray{
    if (!_infoArray) {
        //路线名
        NSString *lineName = nil;
        if (_inspectionLine) {
            lineName = _inspectionLine.inspectionLineName.length?_inspectionLine.inspectionLineName:NSLocalizedString(@"none", nil);
        }else if (self.inspectionLineOption){
            lineName = self.inspectionLineOption.inspectionLineName.length ? self.inspectionLineOption.inspectionLineName : NSLocalizedString(@"none", nil);
        }else{
            lineName = NSLocalizedString(@"none", nil);
        }
        //创建人
        NSString *creator = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"creator", nil),_inspectionLine.creator.userName?:NSLocalizedString(@"none", nil)];
        //巡查间隔
        NSString *timeInterval = [YWCommonTool minuteToHourOrDayString:_inspectionLine.intervalMinute];
        NSString *timeStr = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"inspectionInterval", nil),timeInterval];
        //巡查日
        __block NSString *weekStr = @"";
        [_inspectionLine.weekRels enumerateObjectsUsingBlock:^(YWInspectionLineWeekRel*  _Nonnull weekRel, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx!=0) {
                weekStr = [weekStr stringByAppendingString:@","];
            }
            weekStr = [weekStr stringByAppendingString:[YWCommonTool weekDayString:weekRel.week]];
        }];
        weekStr = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"inspectionDay", nil),weekStr.length?weekStr:NSLocalizedString(@"none", nil)];
        //备注
        NSString *lineNote = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"note", nil),_inspectionLine.note.length ? _inspectionLine.note : NSLocalizedString(@"none", nil)];
        _infoArray = [[NSArray alloc] initWithObjects:lineName,creator,timeStr,weekStr,lineNote, nil];
    }
    return _infoArray;
}

- (NSArray *)timeLineDataArray{
    if (!_timeLineDataArray) {
        NSArray *array = _inspectionLine ? [[YWInspectionMissionManager shareManager] inspectionLineDataWithInspectionLine:_inspectionLine] : nil;
        _timeLineDataArray = array;
    }
    return _timeLineDataArray;
}

#pragma mark - Table view data source
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    if (indexPath.section == 1) {
//        return [tableView fd_heightForCellWithIdentifier:inspectionTimeLineCellIdentifier cacheByIndexPath:indexPath configuration:^(YWInspectionTimeLineCell *cell) {
//            cell.fd_enforceFrameLayout = NO;
//            cell.dicData = self.timeLineDataArray[indexPath.row];
//        }];
//    }else{
//        return 44;
//    }
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return section == 1 ? self.timeLineDataArray.count : self.infoArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        YWInspectionTimeLineCell *cell =[tableView dequeueReusableCellWithIdentifier:inspectionTimeLineCellIdentifier];
        cell.dicData = self.timeLineDataArray[indexPath.row];
        return cell;
    }else{
        static NSString *cellIdentifier = @"YWShowInspectionLineVCReuseCellIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.textLabel.font = kContentFont;
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        }
        cell.textLabel.text = self.infoArray[indexPath.row];
        cell.textLabel.textColor = indexPath.row == 0 ? [UIColor customYellowColor]:[UIColor blackColor];
        return cell;
    }
    
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWAssignInspectionMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return NSLocalizedString(@"lineInfo", nil);//@"路线信息";
    }else if (section==1){
        return NSLocalizedString(@"lineDetail", nil);//@"路线图";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH/2-20*2;
        
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeSystem];
        deleteButton.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        deleteButton.clipsToBounds = YES;
        deleteButton.layer.cornerRadius = 5.0;
        
        [deleteButton setTitle:NSLocalizedString(@"delete", nil) forState:UIControlStateNormal];
        [deleteButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        deleteButton.backgroundColor = [UIColor customRedColor];
        [deleteButton addTarget:self action:@selector(cliclDeleteBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        _deleteButton = deleteButton;
        [_footView addSubview:_deleteButton];
        
        UIButton *modifyButton = [UIButton buttonWithType:UIButtonTypeSystem];
        modifyButton.frame = CGRectMake(20*2+deleteButton.bounds.size.width+20, 30, buttonWidth, kButtonH);
        modifyButton.clipsToBounds = YES;
        modifyButton.layer.cornerRadius = 5.0;
        
        [modifyButton setTitle:NSLocalizedString(@"modify", nil) forState:UIControlStateNormal];
        [modifyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        modifyButton.backgroundColor = [UIColor customBlueColor];
        [modifyButton addTarget:self action:@selector(clickModifyBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        _modifyButton = modifyButton;
        [_footView addSubview:_modifyButton];
    }
    if (self.timeLineDataArray.count==0) {
        [_deleteButton removeFromSuperview];
        [_modifyButton removeFromSuperview];
    }
    return _footView;
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);//@"处理中";
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)cliclDeleteBtnEvent:(id)sender{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToDelete", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self deleteInspectionLine];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)deleteInspectionLine{
    if (_inspectionLine.inspectionLineId>0) {
        [[YWInspectionMissionManager shareManager] deleteInspectionLineWithLineId:_inspectionLine.inspectionLineId completeBlock:^(NSInteger statusCode) {
            [self.HUD hide:YES];
            if (statusCode == 200) {
                [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteSucceed", nil)];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }];
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"canNotDelete", nil)];
    }
}

- (void)clickModifyBtnEvent:(id)sender{
    if (_inspectionLine.inspectionLineId>0) {
        if (_inspectionLine.lineType == YWInspectionLineTypeEquipment) {
            YWModifyEquipmentInspecLineTableViewController *modifyEquLineVC = [[YWModifyEquipmentInspecLineTableViewController alloc] init];
            modifyEquLineVC.inspectionLine = _inspectionLine;
            [self.navigationController pushViewController:modifyEquLineVC animated:YES];
        }else{
            YWModifyLocationInspecLineTableViewController *modifyLocationLineVC = [[YWModifyLocationInspecLineTableViewController alloc] init];
            modifyLocationLineVC.inspectionLine = _inspectionLine;
            [self.navigationController pushViewController:modifyLocationLineVC animated:YES];
        }
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"cantNotFindLine", nil)];
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
